//
//  YOViewPager.swift
//  sss
//
//  Created by hrrMac on 2020/1/6.
//  Copyright © 2020 hrrMac. All rights reserved.
//

import UIKit


///加载方式
enum YOLoadType{
    case openLoad  //打开的时候才加载
    case allLoad   //一次加载所有的
    case aroundLoad  //加载周围的
}


enum YOHeaderType{
    
}


@objc protocol YOViewPagerDelegate : NSObjectProtocol{
    ///所有子视图的数量
    func numberOfPager(_ viewPager: YOViewPager) -> Int
    ///返回子视图对象
    func viewPager(_ viewPager: YOViewPager, viewForPager index: Int) -> UIViewController
    
    @objc optional func viewPager(_ viewPager:YOViewPager, progressForPager prpgress: Float)
    
}


class YOViewPager: UIView {

    let scrollView = UIScrollView()
    let contentView = UIView()
    var loadType:YOLoadType = .allLoad
    
    ///视图的代理
    weak open var delegate: YOViewPagerDelegate?
    
    ///子视图的个数
    var number:Int = 0
    ///所有子视图的控制器
    var viewControllers: [UIViewController] = []
    ///标记是否加载在 openLoad around 下才有效
    var loadMark: [Bool] = []
    
    ///当前页数
    var nowIndex: Int = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.configUI()
    }
        
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        configUI()
//        fatalError("init(coder:) has not been implemented")
    }
    
    func configUI(){
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.showsVerticalScrollIndicator = false;
        scrollView.showsHorizontalScrollIndicator = false;
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        addSubview(scrollView)
        scrollView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
        scrollView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
        scrollView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
        
        configContentView()
    }
    
    func configContentView(){
        contentView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(contentView)
        contentView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        contentView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
        contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
        contentView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
        contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
    }

}


extension YOViewPager{
    
    func reloadData(){
        number = delegate?.numberOfPager(self) ?? 0
        for i in 0 ..< number {
            let vc = delegate?.viewPager(self, viewForPager: i)
            viewControllers.append(vc!)
            if loadType != .allLoad {
                loadMark.append(false)
            }
        }
        switch loadType {
        case .allLoad:
            allDataReload()
        case .openLoad:
            openLoadView()
        case .aroundLoad:
            loadAroundView()
        }
    }
    
    
    func allDataReload(){
        var prevLeftAnchor = contentView.leftAnchor
        for i in 0 ..< number {
            let vc = viewControllers[i]
            let vi = vc.view!
            vi.translatesAutoresizingMaskIntoConstraints = false
            contentView.addSubview(vi)
            vi.leftAnchor.constraint(equalTo: prevLeftAnchor).isActive = true
            vi.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
            vi.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
            vi.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
            prevLeftAnchor = vi.rightAnchor
            if i == number - 1 {
                vi.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
            }
        }
    }
    
    func openLoadView(){
        if number > 1 {
            loadMark[0] = true
            let sizeWidth = CGFloat(CGFloat(number - 1) * CGFloat(self.frame.size.width)) * -1
            let vc = viewControllers.first
            let vi = vc!.view!
            vi.translatesAutoresizingMaskIntoConstraints = false
            contentView.addSubview(vi)
            vi.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
            vi.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
            vi.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
            vi.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
            vi.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: sizeWidth).isActive = true
            
        }
    }
    
    func loadAroundView(){
        if number > 2 {
            addView(1)
        }
    }
    
    ///添加视图到scrollView 上面
    func addView(_ index: Int){
        if loadMark[index] || index < 0 || index >= number {
            return
        }
        print("添加\(index)")
        loadMark[index] = true
        let vc = viewControllers[index]
        let vi = vc.view!
        let sizeWidth = CGFloat(CGFloat(index) * CGFloat(self.frame.size.width))
        vi.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(vi)
        vi.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: sizeWidth).isActive = true
        vi.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
        vi.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
        vi.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
    }
    
    
}


extension YOViewPager:UIScrollViewDelegate{
    ///滑动过程就会调用
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
    
    ///减速滑动的时候调用
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollEnd()
    }
    
    //滚动完毕就会调用（如果不是人为拖拽scrollView导致滚动完毕，才会调用这个方法）
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        scrollEnd()
    }
    
    
    func scrollEnd(){
        if loadType == .allLoad {
            return
        }
        let index = Int(scrollView.contentOffset.x / self.frame.size.width)
        setNowIndex(index: index)
    }
    
}


///处理滑动后当前界面的选择等其他时间
extension YOViewPager{
    
    ///选择当前的视图，处理界面滑动加载等事件
    func setNowIndex(index :Int , animated :Bool = true){
        nowIndex = index
        addView(index)
        scrollView.setContentOffset(CGPoint(x: CGFloat(CGFloat(nowIndex) * CGFloat(self.frame.size.width)), y: 0), animated: animated)
    }
    
}

